/**
 * 行政机构选择器
 */
import React from 'react';
import { Spin, TreeSelect } from 'antd';
import { useRequest } from '@/hooks';
import { fetchCompany } from '../service';

const getTreeData = (
    data = [],
    fieldsName = { value: 'organizationCode', title: 'organizationName' },
    disabledKeys = []
) =>
    data?.map(item => ({
        ...item,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        disabled: disabledKeys.includes(item[fieldsName.value]),
        children: item.children ? getTreeData(item.children, fieldsName, disabledKeys) : item.children
    }));

const Company = React.forwardRef(
    ({ value, onChange, requestParams, style, disabledKeys, permissionsLimit = true, ...rest }, ref) => {
        const { data, loading } = useRequest(() =>
            fetchCompany({
                organizationPermissions: permissionsLimit ? 1 : 0,
                showTreeFlag: 1,
                ...requestParams
            })
        );

        const treeData = React.useMemo(() => {
            const finalData = Array.isArray(data?.data) ? data?.data : [];
            return getTreeData(finalData, undefined, disabledKeys);
        }, [data, disabledKeys]);

        const finalValue = value === '' ? undefined : value;

        return (
            <Spin spinning={loading}>
                <TreeSelect
                    ref={ref}
                    value={finalValue}
                    onChange={onChange}
                    treeData={treeData}
                    allowClear
                    placeholder="请选择行政机构"
                    showSearch
                    treeNodeFilterProp="title"
                    treeDefaultExpandAll
                    style={{ width: 170, ...style }}
                    dropdownStyle={{ maxHeight: 250, overflowY: 'visible' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    {...rest}
                />
            </Spin>
        );
    }
);

export default Company;
